import { Component } from '@angular/core';
import { IonicPage, NavController, PopoverController } from 'ionic-angular';

import { IndexedDBService } from '../../services/indexeddb.service'
import { TopicView } from '../../model/topicView'
import { TopicMessage } from '../../model/topicMessage'

@IonicPage()
@Component({
	selector: 'page-home',
	templateUrl: 'home.html'
})
export class HomePage {

	topicViews: TopicView[] = [];
	colorRed: boolean = true;
    colorGreen: boolean = false;
	colorBlue: boolean = true;
	isClear: string = "red";

	constructor(
		public navCtrl: NavController,
		private popCtrl: PopoverController,
		private indexedDb: IndexedDBService
	) {

		let self = this;
		indexedDb.getAllDate("communications")
		.then((result:any) => {
			result.forEach(element => {
				let tv = new TopicView(element);
				tv.updateUserInfo(self.indexedDb.userInfors);
				self.topicViews.push(tv);
			});
		});
	}

	popupMessageOptions(event, tv: TopicView): void {
		console.log(event);
		// console.log(tv);
		let popover = this.popCtrl.create(
			"HomePopupPage", 
			{
				topicView: tv,
				callback: {
					topMessage: () => {this.topMessage(tv.commuUserId)},
					markMessage: () => {this.markMessage(tv.commuUserId)},
					deleteMessage: () => {this.deleteMessage(tv.commuUserId)},
					doNothing: () => {this.setTopicViewStatus(tv, false)}
				},
			}
		);
		popover.present({ev:event});
	}

	setTopicViewStatus(tv: TopicView, isForce: boolean): void {
		// console.log("HomePage setTopicViewStatus");
		if(isForce) {
			tv.status = "item-focus"
		} else {
			if(tv.isTop == 0) {
				tv.status = "";
			} else {
				tv.status = "item-top";
			}	
		}
	}

	topicDetail(tv: TopicView): void {

		this.indexedDb.getAllDate(tv.topicType + tv.commuUserId)
		.then((result:any) => {
			let list = [];
			result.forEach(element => {
				let tm = new TopicMessage(element);
				list.push(tm);
			});
			
			this.navCtrl.push('TopicPage', {
				topicView: tv,
				topicMessages: list
			});
		});
	}

	topMessage(topicViewId: string): void {

	}

	markMessage(topicViewId: string): void {

	}

	deleteMessage(topicViewId: string): void {
		
	}

	ionViewDidLoad(): void {
		console.log("HomePage ionViewDidLoad");
	}

}
